package com.atfusu.service.impl;

import com.atfusu.base.BaseDao;
import com.atfusu.base.impl.BaseServiceImpl;
import com.atfusu.bean.entity.AdminRole;
import com.atfusu.bean.entity.Role;
import com.atfusu.dao.AdminDao;
import com.atfusu.dao.AdminRoleDao;
import com.atfusu.dao.RoleDao;
import com.atfusu.service.RoleService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Title:
 * Author: fusu
 * DateTime:  2022/11/24
 * Description:
 **/
@DubboService
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private AdminRoleDao adminRoleDao;


    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }

    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {
        //①找出所有的角色
        List<Role> roleList = roleDao.findAll();
        //②再根据adminId找到对应的角色id
        List<Long> roleIds = adminRoleDao.findRoleIdsByAdminId(adminId);
        //③进行划分（已有角色/未有角色）
        List<Role> noAssignRoleList = new ArrayList<>();
        List<Role> assignRoleList = new ArrayList<>();
        for (Role role : roleList) {
            if (roleIds.contains(role.getId())) {
                assignRoleList.add(role);
            } else {
                noAssignRoleList.add(role);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("noAssignRoleList", noAssignRoleList);
        map.put("assignRoleList", assignRoleList);
        return map;
    }

    @Override
    public void saveAdminRoleRelationship(Long adminId, Long[] roleIds) {
        //①删除数据库内已有的对应关系
        adminRoleDao.deleteByAdminId(adminId);
        //②将调整后的所有对应关系存入
        for (Long roleId : roleIds) {
            if (roleId != null) {
                //循环添加对应关系
                AdminRole adminRole = new AdminRole();
                adminRole.setAdminId(adminId);
                adminRole.setRoleId(roleId);
                adminRoleDao.insert(adminRole);
            }
        }
    }
}
